import { Form, Button, Select, Input, Modal, message, Radio, Row, Col } from 'antd'
import React, { useState, useImperativeHandle } from 'react'
import { useStore } from '@/store'
import { http } from '@/utils'
import { PlusOutlined, MinusOutlined } from '@ant-design/icons'
const { TextArea } = Input
const Addmodal = ((props) => {
  const [title, setTitle] = useState(null)
  const [showModalOpen, setShowModalOpen] = useState(false)
  const { loginStore } = useStore()
  const [form] = Form.useForm()
  const [formData, setFormData] = useState({})
  const handleOk = () => {
    setShowModalOpen(false)
  }
  const handleCancel = () => {
    setShowModalOpen(false)
  }

  // 父组件调用打开模态框
  useImperativeHandle(props.onRef, () => {
    return {
      openModalOpen: openModalOpen,
    }
  })
  // 打开model 初始化
  const openModalOpen = (data) => {
    form.resetFields()
    const subAccount = data && data.subAccount.length ? data.subAccount.map((item, i) => {
      return {
        ...item,
        account: item.username,
        key: i + 1,
        accountStatus: '',
        passwordStatus: '',
      }
    }) : [
      { account: '', password: '', accountStatus: '', passwordStatus: '', key: 1 }
    ]
    let objData = data ? {
      ...data,
      groupId: data.id,
      subAccountType: data.subAccountType ? data.subAccountType : 1,
      subAccountList: subAccount
    } : {
      groupId: null,
      subAccountList: subAccount
    }
    if (!data) {
      setTitle('添加预警组')
    } else {
      form.setFieldsValue(objData)
      setTitle('编辑预警组')
    }
    console.log(objData)
    setFormData(objData)
    setShowModalOpen(true)
  }

  // submit
  const onFinish = async (values) => {
    console.log(values)
    let empty = false
    for (let index = 0; index < formData.subAccountList.length; index++) {
      const element = formData.subAccountList[index]
      if (!element.account && values.groupType === 2 && values.subAccountType === 2) {
        // element.accountStatus = 'error'
        empty = true
      }
      if (!element.password && values.groupType === 2 && values.subAccountType === 2) {
        // element.passwordStatus = 'error'
        empty = true
      }
    }
    console.log({
      ...values,
      subAccountList: formData.subAccountList
    })
    if (empty) {
      message.warning('请输入未填项')
      return
    }
    setFormData({
      ...formData,
      subAccountList: formData.subAccountList
    })
    const res = await http.post('/alarm/deliversign/addOrUpdateAlarmGroupInfo', {
      groupId: formData.groupId,
      userId: loginStore.userId,
      ...values,
      subAccountList: values.groupType === 2 && values.subAccountType === 2 ? formData.subAccountList : []
    })
    message.success(res.body)
    setShowModalOpen(false)
    props.changeAddorupdata('配置成功更新列表')
  }
  // 分仓账号 双向绑定
  const accountOnchange = (e, row) => {
    const data = formData.subAccountList.map(item => {
      const list = {
        ...item
      }
      if (row.key === item.key) {
        list.account = e.target.value
      }
      return list
    })
    setFormData({ ...formData, subAccountList: data })
  }

  // 分仓密码 双向绑定
  const passwordOnchange = (e, row) => {
    const data = formData.subAccountList.map(item => {
      const list = {
        ...item
      }
      if (row.key === item.key) {
        list.password = e.target.value
      }
      return list
    })
    setFormData({ ...formData, subAccountList: data })
  }
  // 删除分仓账号
  const delSubAccountList = (i, row) => {
    const data = formData.subAccountList.filter(item => {
      return item.key !== row.key
    })
    setFormData({ ...formData, subAccountList: data })
  }
  // 添加分仓账号
  const addSubAccountList = (i, item) => {
    setFormData({
      ...formData,
      subAccountList: [
        ...formData.subAccountList,
        { account: '', password: '', accountStatus: '', passwordStatus: '', key: formData.subAccountList[formData.subAccountList.length - 1].key + 1 }
      ]
    })
  }

  return (
    <>
      {/* forceRender Modal未弹出时强制渲染  处理form hooks 动态赋值问题 */}
      <Modal
        forceRender
        title={title}
        open={showModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={false}
        width={700}
      >
        <Form
          form={form}
          colon={false}
          validateTrigger={['onBlur', 'onChange']}
          onFinish={onFinish}
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          style={{
            marginTop: 30,
            maxWidth: 550,
          }}
        >
          <Form.Item
            label="预警品种"
            name="groupType"
            rules={[
              {
                required: true,
                message: '请选择品种',
              }
            ]}
          >
            <Select
              onChange={(val) => setFormData({ ...formData, groupType: val })}
              style={{ width: 260 }}
              allowClear
              placeholder="请选择"
              options={[
                { value: 1, label: '手工添加' },
                { value: 2, label: '自动更新' }
              ]}
            />
          </Form.Item>
          <Form.Item
            label="预警组名称"
            name="groupAlarmName"
            rules={[
              {
                required: true,
                message: '请输入预警组名称',
              }
            ]}>
            <Input
              allowClear
              placeholder='请输入预警组名称'
              style={{ width: 260 }}
            />
          </Form.Item>
          {
            formData.groupType === 2 ? (
              <>
                <Form.Item label=" " name="subAccountType" rules={[{ required: true, message: '请选择', }]}>
                  <Radio.Group onChange={(e) => setFormData({ ...formData, subAccountType: e.target.value })}>
                    <Radio value={1}>条件选股</Radio>
                    <Radio value={2}>分仓系统</Radio>
                  </Radio.Group>
                </Form.Item>
                {
                  formData.subAccountType === 1 ? <>
                    <Form.Item label="自动更新标识" name="updateFlag">
                      <Input
                        allowClear
                        placeholder='请输入自动更新标识'
                        style={{ width: 260 }}
                      />
                    </Form.Item>
                  </> : ''
                }
                {
                  formData.subAccountType === 2 ? formData.subAccountList.map((item, i) => {
                    return (
                      <div key={item.key}>
                        <Row style={{ marginBottom: 10 }}>
                          <Col span={7} style={{ textAlign: 'right', lineHeight: '32px', paddingRight: '8px' }}>
                            账号 {item.key} {item.passwordStatus}
                          </Col>
                          <Col span={7}>
                            <Input
                              allowClear
                              placeholder='请输入用户名'
                              style={{ width: 150 }}
                              status={item.accountStatus}
                              value={item.account}
                              onChange={(e) => accountOnchange(e, item)}
                            />
                          </Col>
                          <Col span={7}>
                            <Input
                              allowClear
                              placeholder='请输入密码'
                              style={{ width: 150 }}
                              status={item.passwordStatus}
                              value={item.password}
                              onChange={(e) => passwordOnchange(e, item)}
                            />
                          </Col>
                          <Col span={3} style={{ paddingTop: '4px' }}>
                            <Button icon={<PlusOutlined />} size="small" style={{ marginRight: 5 }} onClick={() => addSubAccountList(i, item)} />
                            {i !== 0 ? <Button icon={<MinusOutlined />} size="small" onClick={() => delSubAccountList(i, item)} /> : ''}
                          </Col>
                        </Row>
                      </div>
                    )
                  }) : ''
                }
              </>
            ) : ''
          }
          <Form.Item label="备注" name="mark" >
            <TextArea
              placeholder='请输入关键字'
              style={{ width: 260 }}
              rows={4} />
          </Form.Item>
          <Form.Item label=" ">
            <Button htmlType="submit" type="primary">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal >
    </>
  )
})
export default Addmodal